<template>
	<view>
    <uni-list>
      <uni-list-item showArrow @tap="onAvatarTap" link>
        <template v-slot:header>
          <view class="d-flex a-center">头像</view>
        </template>
        <template v-slot:footer>
          <image class="rounded" style="height: 80rpx; width: 80rpx;" :src="avatar?avatar:'/static/avatar.jpeg'" mode="widthFix">
          </image>
        </template>
      </uni-list-item>
      <uni-list-item @tap="onUsernameTap" showArrow title="用户名" :rightText="authStore.user.username" link></uni-list-item>
    </uni-list>

		<uni-popup ref="dialogUsername" type="dialog">
				<uni-popup-dialog mode="input" title="修改用户名" :value="username"
					placeholder="请输入用户名" @confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>

import { ref } from 'vue'
import useAuthStore from '../../stores/auth'
import UniListItem from "../../uni_modules/uni-list/components/uni-list-item/uni-list-item.vue";
import userHttp from '../../apis/user/userHttp'
import UniList from "../../uni_modules/uni-list/components/uni-list/uni-list.vue";
const authStore = useAuthStore()
let user = authStore.user;
const avatar = user.avatar
const username = user.username
let dialogUsername = ref()
const base_user_url = import.meta.env.VITE_BASE_USER_URL
const onAvatarTap = () => {
  uni.chooseImage({
    count: 1,
    success(chooseImageRes) {
      const tempFilePaths = chooseImageRes.tempFilePaths;
      uni.showLoading({
        title: "上传中..."
      })
      uni.uploadFile({
        url: base_user_url + '/user/update/avatar',
        header: {
          Authorization: "Bearer " + authStore.access_token
        },
        filePath: tempFilePaths[0],
        name: 'file',
        success: (uploadFileRes) => {
          const data = JSON.parse(uploadFileRes.data)
          let user = authStore.user
          user.avatar = data.file_url
          authStore.setUser(user);
          uni.hideLoading();
        },
        fail: (error) => {
          uni.hideLoading();
          console.log(error)
        }
      });
    }
  })
}

const onUsernameTap = () => {
	dialogUsername.value.open()
}
const dialogInputConfirm = async (value) => {
	let result = await userHttp.updateUsername(value)
  user.username = value
  authStore.setUser(user)
  if (result['result'] == 1) {
      uni.showToast({
        title: '用户名修改成功！',
        icon: "success"
      })
  }
}
</script>

<style></style>
